package songZhao.MinaDemo.Example;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class ExampleClient {
	final static int num = 127;

	public static void main(String[] args) {
		IoConnector connector = new NioSocketConnector();
		connector.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(new ExampleProtocolFactory(Charset.forName("UTF-8"))));
		connector.getSessionConfig().setReadBufferSize(1024);
		connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,10);
		connector.setHandler(new ClientHandler());
		ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1",7080));
		future.addListener(new IoFutureListener<ConnectFuture>() {
			@Override
			public void operationComplete(ConnectFuture future) {
				if (future.isConnected()) {
					IoSession session = future.getSession();
					sendData(session);
				}
			}
		});
	}
	public static void sendData(IoSession session) {
		for (int i = 0; i < 20; i++) {
			String temp = "data "+i;
			ProtocolPack pack = new ProtocolPack((byte) i, temp);
			session.write(pack);	
			System.out.println("Client sent :"+pack);
		}
	}
	
}
class ClientHandler extends IoHandlerAdapter{

	@SuppressWarnings("deprecation")
	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		if (status == IdleStatus.READER_IDLE) {
			session.close();
		}
	}

}